package com.plian.system.service.qg.guarantee.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.DictCache;
import com.plian.system.cache.OrgCache;
import com.plian.system.common.status.CheckStatus;
import com.plian.system.common.status.CustomCode;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dto.qg.guarantee.PropertyGuaranteeExecuteDTO;
import com.plian.system.entity.qg.guarantee.PropertyGuaranteeApply;
import com.plian.system.entity.qg.guarantee.PropertyGuaranteeExecute;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.qg.guarantee.PropertyGuaranteeExecuteMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ObjResult;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.service.qg.guarantee.IPropertyGuaranteeApplyService;
import com.plian.system.service.qg.guarantee.IPropertyGuaranteeExecuteService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.qg.guarantee.AmountAnalysisVO;
import com.plian.system.vo.qg.guarantee.PropertyGuaranteeExecuteVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.qg.guarantee.PropertyGuaranteeExecuteWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.GZW_TYPE;
import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 企业担保执行主表 服务实现类
 *
 * @author jianglei
 * @since 2019-10-24
 */
@Slf4j
@Service
@AllArgsConstructor
public class PropertyGuaranteeExecuteServiceImpl extends BaseServiceImpl<PropertyGuaranteeExecuteMapper, PropertyGuaranteeExecute> implements IPropertyGuaranteeExecuteService, BaseFlowService {

    private IPropertyGuaranteeApplyService propertyGuaranteeApplyService;

	private PropertyGuaranteeExecuteMapper propertyGuaranteeExecuteMapper;

	private FormWorkflowService formWorkflowService;

	private IFormCodeService formCodeService;

	private PropertyGuaranteeExecuteWrapper propertyGuaranteeExecuteWrapper;

	private IOrgService orgService;

	private IApprovalMessageService approvalMessageService;

	@Override
    public boolean saveOrUpdate(PropertyGuaranteeExecute propertyGuaranteeExecute) {
		if (!Optional.ofNullable(propertyGuaranteeExecute.getId()).isPresent()){
			propertyGuaranteeExecute.setVersion("1");
			propertyGuaranteeExecute.setCode(formCodeService.getCode(FormTypeConstant.QG_GUARANTEE_EXECUTE_FORM));
			propertyGuaranteeExecute.setFormType(String.valueOf(FormTypeConstant.QG_GUARANTEE_EXECUTE_FORM));
			propertyGuaranteeExecute.setIsEnd(1);
		}
		if (!Optional.ofNullable(propertyGuaranteeExecute.getStatus()).isPresent()) {
			propertyGuaranteeExecute.setStatus(FormStatusConstant.UNREVIEWED);
		}
		changeGuaranteeDate(propertyGuaranteeExecute.getUpstreamCodeId(), propertyGuaranteeExecute.getGuaranteeStartDate(), propertyGuaranteeExecute.getGuaranteeEndDate());
        return super.saveOrUpdate(propertyGuaranteeExecute);
    }

    @Override
    public boolean deleteLogic(List<Long> ids) {
    for (Long id : ids) {
        PropertyGuaranteeExecute propertyGuaranteeExecute = getById(id);
        if (propertyGuaranteeExecute == null) {
            return false;
        } else if (propertyGuaranteeExecute.getStatus() != null &&
				(propertyGuaranteeExecute.getStatus() != FormStatusConstant.STASH && propertyGuaranteeExecute.getStatus() != FormStatusConstant.UNREVIEWED)) {
			return false;
		}
		formWorkflowService.deleteProcessInstance(String.valueOf(id));
    }
    return super.deleteLogic(ids);
    }

    @Override
    public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW,null);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"审批通过");
    }

    @Override
    public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState,null);
    }

	@Override
	public Boolean checkIsExisted(Long id, String code) {
		if (Optional.ofNullable(code).isPresent()) {
			PropertyGuaranteeExecute propertyGuaranteeExecute = new PropertyGuaranteeExecute();
			propertyGuaranteeExecute.setCode(code);
			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(propertyGuaranteeExecute))).isPresent()) {
				if (id==null || !id.equals(getOne(Condition.getQueryWrapper(propertyGuaranteeExecute)).getId())){
					return false;
				}
			}
		}

		return true;
	}
	@Override
	public java.io.File exportExcel(JSONObject jsonObject) {
		List<SearchEntity> entityList = Optional.ofNullable(jsonObject.getJSONArray("query"))
			.map(x -> x.toJavaList(SearchEntity.class)).orElse(new ArrayList<>());
		QueryWrapper<PropertyGuaranteeExecute> qw= SearchParamEntiy.getQueryWrapper(
			Condition.getQueryWrapper(new PropertyGuaranteeExecute()), entityList
		);

		List<PropertyGuaranteeExecute> floors = list(qw);
		return null;
		//return ExcelUtils.exportExcelByList(jsonObject, PropertyGuaranteeExecuteWrapper.build().listVO(floors));
	}
	@Override
	public String checkUpstreamCode(Long id, String upstreamCode, BigDecimal useAmount) {

		if (Optional.ofNullable(upstreamCode).isPresent()) {
			LambdaQueryWrapper<PropertyGuaranteeApply> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(PropertyGuaranteeApply::getCode, upstreamCode);
			queryWrapper.eq(PropertyGuaranteeApply::getStatus, FormStatusConstant.FINISH);
			PropertyGuaranteeApply propertyGuaranteeApply = propertyGuaranteeApplyService.getOne(queryWrapper);

			if (!Optional.ofNullable(propertyGuaranteeApply).isPresent()){
				return "上游单据不存在";
			}
		}
		return null;
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public Boolean submit(PropertyGuaranteeExecute propertyGuaranteeExecute) {

		if (!Optional.ofNullable(propertyGuaranteeExecute.getStatus()).isPresent()){
			propertyGuaranteeExecute.setStatus(FormStatusConstant.UNREVIEWED);
		}
		boolean result = saveOrUpdate(propertyGuaranteeExecute);
		return result;
	}

	@Override
	public String checkSubmit(PropertyGuaranteeExecute propertyGuaranteeExecute) {
		if (!checkIsExisted(propertyGuaranteeExecute.getId(), propertyGuaranteeExecute.getCode())){
			return "单据编码已存在";
		}

		String res = checkUpstreamCode(propertyGuaranteeExecute.getId(), propertyGuaranteeExecute.getUpstreamCode(),
			propertyGuaranteeExecute.getUseAmount());
		if (res != null){
			return res;
		}
		return null;
	}

	@Override
	public ReportReturnVO guaranteeAmountAnalysis(PropertyGuaranteeExecuteDTO propertyGuaranteeExecuteDTO) {

		List<AmountAnalysisVO> amountAnalysisVOS = propertyGuaranteeExecuteMapper.guaranteeAmountAnalysisList(propertyGuaranteeExecuteDTO);
		amountAnalysisVOS.forEach(amountAnalysisVO ->
			amountAnalysisVO.setApplyName(OrgCache.orgIdToName(amountAnalysisVO.getApplyNameId()))
		);
		ReportReturnVO reportReturnVO = new ReportReturnVO();
		reportReturnVO.setCharts(JSONArray.parseArray(JSON.toJSONString(amountAnalysisVOS)));
		return reportReturnVO;
	}

	@Override
	public ReportReturnVO guaranteedAmountAnalysis(PropertyGuaranteeExecuteDTO propertyGuaranteeExecuteDTO) {

		List<AmountAnalysisVO> amountAnalysisVOS = propertyGuaranteeExecuteMapper.guaranteedAmountAnalysisList(propertyGuaranteeExecuteDTO);
		amountAnalysisVOS.forEach(amountAnalysisVO ->
			{
				if (amountAnalysisVO.getFlag() != null && amountAnalysisVO.getFlag() == 1){
					amountAnalysisVO.setApplyName(OrgCache.orgIdToName(amountAnalysisVO.getApplyNameId()));
				}else {
					amountAnalysisVO.setApplyName(amountAnalysisVO.getCompany());
				}
			}

		);

		ReportReturnVO reportReturnVO = new ReportReturnVO();
		reportReturnVO.setCharts(JSONArray.parseArray(JSON.toJSONString(amountAnalysisVOS)));
		return reportReturnVO;
	}

	@Override
	public Boolean checkCancel(Long id) {
		PropertyGuaranteeExecute propertyGuaranteeExecute = getById(id);
		LambdaQueryWrapper<PropertyGuaranteeExecute> executeQueryWrapper = new LambdaQueryWrapper<>();
		executeQueryWrapper.eq(PropertyGuaranteeExecute::getUpstreamCode, propertyGuaranteeExecute.getUpstreamCode());
		executeQueryWrapper.ne(PropertyGuaranteeExecute::getStatus, FormStatusConstant.FINISH);
		if (Optional.ofNullable(getOne(executeQueryWrapper)).isPresent()){
			return false;
		}

		return true;
	}

	@Override
	public ReportReturnVO getExecutes(PropertyGuaranteeExecuteDTO propertyGuaranteeExecuteDTO){
		List<PropertyGuaranteeExecuteVO> propertyGuaranteeExecuteVOS = propertyGuaranteeExecuteMapper.getExecutesList(propertyGuaranteeExecuteDTO);
		List<PropertyGuaranteeExecuteVO> data = new ArrayList<>();
		if (CollectionUtil.isNotEmpty(propertyGuaranteeExecuteVOS)){
			for (PropertyGuaranteeExecuteVO propertyGuaranteeExecuteVO : propertyGuaranteeExecuteVOS){
				propertyGuaranteeExecuteVO.setLoanTypeName(DictCache.dictCodeListToName(propertyGuaranteeExecuteVO.getLoanTypeId()));
			}
			List<PropertyGuaranteeExecuteVO> sumList = new ArrayList<>();
			Map<String, List<PropertyGuaranteeExecuteVO>> map = propertyGuaranteeExecuteVOS.stream().collect(Collectors.groupingBy(PropertyGuaranteeExecuteVO::getGuaranteeName));
			map.forEach((key, value) ->
			{
				data.addAll(value);
				PropertyGuaranteeExecuteVO sum = new PropertyGuaranteeExecuteVO();
				sum.setApprovalNumber("小计：" + value.size());
				for (PropertyGuaranteeExecuteVO vo : value){
					sum.setGuaranteeAmount(BigDecimalUtil.add(sum.getGuaranteeAmount(), vo.getGuaranteeAmount()));
					sum.setLoanAmount(BigDecimalUtil.add(sum.getLoanAmount(), vo.getLoanAmount()));
					sum.setGuaranteeRemain(BigDecimalUtil.add(sum.getGuaranteeRemain(), vo.getGuaranteeRemain()));
					sum.setUseAmount(BigDecimalUtil.add(sum.getUseAmount(), vo.getUseAmount()));
					sum.setTotalLoanAmount(BigDecimalUtil.add(sum.getTotalLoanAmount(), vo.getTotalLoanAmount()));
				}
				sumList.add(sum);
				data.add(sum);
			});
			PropertyGuaranteeExecuteVO end = new PropertyGuaranteeExecuteVO();
			end.setApprovalNumber("总计：" + propertyGuaranteeExecuteVOS.size());
			for (PropertyGuaranteeExecuteVO vo : sumList){
				end.setGuaranteeAmount(BigDecimalUtil.add(end.getGuaranteeAmount(), vo.getGuaranteeAmount()));
				end.setLoanAmount(BigDecimalUtil.add(end.getLoanAmount(), vo.getLoanAmount()));
				end.setGuaranteeRemain(BigDecimalUtil.add(end.getGuaranteeRemain(), vo.getGuaranteeRemain()));
				end.setUseAmount(BigDecimalUtil.add(end.getUseAmount(), vo.getUseAmount()));
				end.setTotalLoanAmount(BigDecimalUtil.add(end.getTotalLoanAmount(), vo.getTotalLoanAmount()));
			}

			data.add(end);

		}

		ReportReturnVO reportReturnVO = new ReportReturnVO();

		ReportVO reportVO = new ReportVO();

		reportVO
			.addHeader(HeaderVO.builder().key("guaranteeCompanyName").title("担保人").build())
			.addHeader(HeaderVO.builder().key("warranteeCompanyName").title("被担保人").build())
			.addHeader(HeaderVO.builder().key("approvalNumber").title("申请批复文号").build())
			.addHeader(HeaderVO.builder().key("guaranteeName").title("担保项目名称").build())
			.addHeader(HeaderVO.builder().key("useAmount").title("本次担保金额（万元）").build())
			.addHeader(HeaderVO.builder().key("guaranteeStartDate").title("担保责任起始日期").build())
			.addHeader(HeaderVO.builder().key("guaranteeEndDate").title("担保责任终止日期").build())
			.addHeader(HeaderVO.builder().key("guaranteeLimit").title("担保期限(月)").build())
			.addHeader(HeaderVO.builder().key("applyName").title("申请公司").build())
			.addHeader(HeaderVO.builder().key("code").title("担保执行单据编号").build())
			.addHeader(HeaderVO.builder().key("totalLoanAmount").title("有息债务余额（万元）").build())
//			.addHeader(HeaderVO.builder().key("guaranteeTotal").title("累计担保额（万元）").build())
			.addHeader(HeaderVO.builder().key("loanAmount").title("本次债务金额（万元）").build())
			.addHeader(HeaderVO.builder().key("loanStartDate").title("本次借款起始日期").build())
			.addHeader(HeaderVO.builder().key("loanEndDate").title("本次借款终止日期").build())
			.addHeader(HeaderVO.builder().key("guaranteeLimit").title("借款期限").build())
			.addHeader(HeaderVO.builder().key("guaranteeRemain").title("剩余担保金额（万元）").build())
			.addHeader(HeaderVO.builder().key("guaranteeModeName").title("担保方式").build())
			.addHeader(HeaderVO.builder().key("guaranteeDutyName").title("担保责任").build())
			.addHeader(HeaderVO.builder().key("loanTypeName").title("借款资金种类").build());

		reportVO.setData(data);
		reportReturnVO.setGrids(reportVO);
		return reportReturnVO;
	}

	@Override
	public IPage<PropertyGuaranteeExecute> parentList(IPage<PropertyGuaranteeExecute> page, QueryWrapper<PropertyGuaranteeExecute> queryWrapper) {
		return page.setRecords(baseMapper.parentList(page,queryWrapper));
	}

	@Override
	public List<PageData> findByIds(List<String> formIds) {
		LambdaQueryWrapper<PropertyGuaranteeExecute> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(PropertyGuaranteeExecute::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
		List<PropertyGuaranteeExecute> enterpriseEmployments = list(queryWrapper);
		List<PropertyGuaranteeExecuteVO> propertyGuaranteeExecuteVOS = propertyGuaranteeExecuteWrapper.entityToVO(enterpriseEmployments);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(propertyGuaranteeExecuteVOS)){
				for (PropertyGuaranteeExecuteVO vo : propertyGuaranteeExecuteVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getApplyName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getApplyNameId());
					pd.put("formType", FormTypeConstant.QG_GUARANTEE_EXECUTE_FORM);
					pd.put("orgName", vo.getApplyName());
					pageDataList.add(pd);
				}
			}

			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Arrays.asList(FormTypeConstant.QG_GUARANTEE_EXECUTE_FORM);
	}

	@Override
	public ObjResult executeFinish(Long id) {
		PropertyGuaranteeExecute propertyGuaranteeExecute = getById(id);

		if (!Optional.ofNullable(propertyGuaranteeExecute).isPresent()){
			return new ObjResult(CustomCode.builder().message("该单据不存在").code(1999).success(false).build());
		}

		if (propertyGuaranteeExecute.getStatus() != FormStatusConstant.FINISH){
			return new ObjResult(CustomCode.builder().message("该单据未审批").code(1999).success(false).build());
		}
		if (propertyGuaranteeExecute.getIsEnd() == 2){
			return new ObjResult(CustomCode.builder().message("该单据已结束担保").code(1999).success(false).build());
		}

		if (Optional.ofNullable(propertyGuaranteeExecute.getIsAdd()).isPresent() && propertyGuaranteeExecute.getIsAdd() == 2){
			//还款后增加剩余担保金额
			PropertyGuaranteeApply propertyGuaranteeApply = propertyGuaranteeApplyService.getById(propertyGuaranteeExecute.getUpstreamCodeId());
			//剩余担保金额+旧数据
			propertyGuaranteeApply.setGuaranteeRemain(propertyGuaranteeApply.getGuaranteeRemain().add(propertyGuaranteeExecute.getUseAmount()));
			propertyGuaranteeApplyService.updateById(propertyGuaranteeApply);
		}
		propertyGuaranteeExecute.setIsEnd(2);
		propertyGuaranteeExecute.setGuaranteeActualDate(DateUtil.now());
		return  updateById(propertyGuaranteeExecute) ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
	}

	@Override
	public void goBackToStash(String formId) {
//		cancel(Long.valueOf(formId));
		handleStatus(Long.valueOf(formId), UNREVIEWED,null);
	}

	/**
     * 统一处理状态机事件方法
     * @param id 主键
     * @param updateStatus 更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus,String comment) {
        try {
            PropertyGuaranteeExecute propertyGuaranteeExecute = getById(id);
			/**
			 * 设置审批人和审批时间
			 */
			if (updateStatus == FormStatusConstant.FINISH){
				propertyGuaranteeExecute.setApprovedUser(TokenUtil.getTokenUserId());
				Date now = DateUtil.now();
				propertyGuaranteeExecute.setApprovedTime(now);
			}
			if (StringUtil.isNotBlank(propertyGuaranteeExecute.getDataSource()) &&
					StringUtil.isNotBlank(propertyGuaranteeExecute.getDataSourceId())
					&& !propertyGuaranteeExecute.getDataSource().equals(YthConstant.DATA_NINGBO)){
				if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
					ApprovalMessage approvalMessage = new ApprovalMessage();
					approvalMessage.setDataSourceId(propertyGuaranteeExecute.getDataSourceId());
					approvalMessage.setOpinion(comment);
					approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
					approvalMessage.setIsSend(1);
					approvalMessage.setDataSourceType(GZW_TYPE);
					approvalMessage.setFilingCode(propertyGuaranteeExecute.getCode());
					approvalMessageService.save(approvalMessage);
				}
			}
            propertyGuaranteeExecute.setStatus(updateStatus);
            updateById(propertyGuaranteeExecute);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

    private boolean changeGuaranteeDate(Long guaranteeApplyId, Date guaranteeStartDate, Date guaranteeEndDate){
		List<PropertyGuaranteeExecute> list = list(new LambdaQueryWrapper<PropertyGuaranteeExecute>()
				.eq(PropertyGuaranteeExecute::getUpstreamCodeId, guaranteeApplyId));
		if (CollectionUtil.isNotEmpty(list)){
			List<Date> guaranteeStartDates = list.stream().map(PropertyGuaranteeExecute::getGuaranteeStartDate).collect(Collectors.toList());
			List<Date> guaranteeEndDates = list.stream().map(PropertyGuaranteeExecute::getGuaranteeEndDate).collect(Collectors.toList());
			DateFormat df = new SimpleDateFormat(DateUtil.PATTERN_DATETIME);
			SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.PATTERN_DATETIME);
			guaranteeStartDates.add(guaranteeStartDate);

			//开始时间正序排
			guaranteeStartDates.sort((a1, a2) -> {
				try {
					return df.parse(sdf.format(a1)).compareTo(df.parse(sdf.format(a2)));
				} catch (Exception e) {
					log.error(ExceptionUtils.getFullStackTrace(e));
				}
				return 1;
			});
			guaranteeStartDate = guaranteeStartDates.get(0);

			//结束时间倒序排
			guaranteeEndDates.add(guaranteeEndDate);
			guaranteeEndDates.sort((a1, a2) -> {
				try {
					return df.parse(sdf.format(a2)).compareTo(df.parse(sdf.format(a1)));
				} catch (Exception e) {
					log.error(ExceptionUtils.getFullStackTrace(e));
				}
				return 1;
			});
			guaranteeEndDate = guaranteeEndDates.get(0);
		}

		return propertyGuaranteeApplyService.update(new LambdaUpdateWrapper<PropertyGuaranteeApply>()
				.set(PropertyGuaranteeApply::getGuaranteeStartDate, guaranteeStartDate)
				.set(PropertyGuaranteeApply::getGuaranteeEndDate, guaranteeEndDate)
				.eq(PropertyGuaranteeApply::getId, guaranteeApplyId));
	}

	@Override
	public String saveGuaranteeExecuteList(String data) {
		YthResult ythResult = new YthResult();
		//成功的id集合
		List<String> successIds = new ArrayList<>();
		//失败的id集合
		List<String> failIds = new ArrayList<>();
		//失败的原因
		List<String> failReasons = new ArrayList<>();
		//将json字符串转换成list
		List<PropertyGuaranteeExecute> dataList = JSON.parseArray(data, PropertyGuaranteeExecute.class);
		if (CollectionUtil.isNotEmpty(dataList)){
			Map<String, String> orgSource = orgService.getSourceId();
			//根据datasourceIds 查询出所有的数据
			List<PropertyGuaranteeExecute> list = list(new LambdaQueryWrapper<PropertyGuaranteeExecute>().in(PropertyGuaranteeExecute::getDataSourceId, dataList.stream().map(PropertyGuaranteeExecute::getDataSourceId).toArray()));
			//如果数据库中有数据，就更新，没有就新增
			for (PropertyGuaranteeExecute entity:dataList){
				entity.setVersion("1");
				entity.setCode(formCodeService.getCode(FormTypeConstant.QG_GUARANTEE_EXECUTE_FORM));
				entity.setFormType(String.valueOf(FormTypeConstant.QG_GUARANTEE_EXECUTE_FORM));
				entity.setIsEnd(1);

				String result = checkSubmit(entity);

				if (StringUtil.isNotBlank(result)){
					failIds.add(entity.getDataSourceId());
					failReasons.add("dataSourceId:"+entity.getDataSourceId()+ result);
				}else {
					//id重复略过
					transfer(entity,orgSource);
					if (CollectionUtil.isNotEmpty(list)){
						List<String> olIds = list.stream().map(PropertyGuaranteeExecute::getDataSourceId).collect(Collectors.toList());
						String dataSourceId = entity.getDataSourceId();
						//判断数据库中是否有数据
						if (olIds.contains(dataSourceId)){
							for (PropertyGuaranteeExecute oldEntity:list){
								if (dataSourceId.equals(oldEntity.getDataSourceId())){
									PropertyGuaranteeExecute old = getById(oldEntity.getId());
									result = propertyGuaranteeApplyService.checkExecute(entity.getUpstreamCodeId(),old,entity);
									if (StringUtil.isNotBlank(result)){
										failIds.add(dataSourceId);
										failReasons.add("dataSourceId:"+dataSourceId+result);
									}else {
										//判断status是否为0，如果是0，就更新，不是0，就不更新
										if (CheckStatus.checkCode(oldEntity.getStatus())){
											successIds.add(dataSourceId);
											entity.setId(oldEntity.getId());
											entity.setDataSource(YthConstant.DATA_NINGBO);
											submit(entity);
											list.remove(oldEntity);
											break;
										}else {
											failIds.add(dataSourceId);
											failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
											break;
										}
									}
								}
							}
						}else {
							//如果数据库中没有数据，就新增
							entity.setDataSource(YthConstant.DATA_NINGBO);
							submit(entity);
							successIds.add(entity.getDataSourceId());
						}
					}else {
						//如果数据库中没有数据，就新增
						entity.setDataSource(YthConstant.DATA_NINGBO);
						submit(entity);
						successIds.add(entity.getDataSourceId());
					}
				}
			}
		} else {
			failReasons.add("数据为空");
		}
		ythResult.setSuccessIds(successIds);
		ythResult.setFailIds(failIds);
		ythResult.setFailReason(StringUtils.join(failReasons, ";"));
		//ythResult转换成json字符串
		return JSON.toJSONString(ythResult);
	}

	private void transfer(PropertyGuaranteeExecute entity, Map<String, String> orgSourceMap){
		Optional.ofNullable(entity.getApplyNameId()).ifPresent(m ->
				{
					String orgId = orgSourceMap.get(m);
					entity.setApplyNameId(orgId);
					entity.setCreateCompanyId(orgId);
				}
		);


		Optional.ofNullable(entity.getUpstreamCodeId()).ifPresent(applyId ->
				{
					PropertyGuaranteeApply propertyGuaranteeApply = propertyGuaranteeApplyService.getOne(new LambdaQueryWrapper<PropertyGuaranteeApply>()
							.eq(PropertyGuaranteeApply::getDataSourceId,applyId));
					Optional.ofNullable(propertyGuaranteeApply).ifPresent(apply ->{
						entity.setUpstreamCode(apply.getCode());
						entity.setGuaranteeCompanyId(apply.getGuaranteeCompanyId());
						entity.setWarranteeCompanyName(apply.getWarranteeCompanyName());
						entity.setGuaranteeAmount(apply.getGuaranteeAmount());
						entity.setGuaranteeModeId(apply.getGuaranteeModeId());
						entity.setGuaranteeDutyId(apply.getGuaranteeDutyId());
						entity.setGuaranteeStartDate(apply.getGuaranteeStartDate());
						entity.setGuaranteeEndDate(apply.getGuaranteeEndDate());
						entity.setGuaranteeLimit(apply.getGuaranteeLimit().toString());
						entity.setLoanTypeId(apply.getLoanTypeId());
						entity.setLoanNatureId(apply.getLoanNatureId());
						entity.setGuaranteeCompanyId(apply.getGuaranteeCompanyId());
					});
				}
		);

	}
}
